package com.yh.homestay.controller;

import com.yh.homestay.common.JsonUtils;
import com.yh.homestay.common.PictureResult;
import com.yh.homestay.common.QiNiuUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Api(description = "上传")
public class PictureController {
    /*@Autowired
    FastDFSUtil fastDFSUtil;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public String picUpload(MultipartFile uploadFile) {
        PictureResult pictureResult = new PictureResult();
        try {
            String uploadPath = fastDFSUtil.uploadFile(uploadFile);
            String ss = uploadPath;
            String[] split = ss.split(":22122");
            String url = split[0] + split[1];
            System.out.println(split[0] + split[1]);
            pictureResult.setCode(0);
            pictureResult.setMsg("上传成功");
            Map map = new HashMap();
            map.put("src", url);
            pictureResult.setData(map);
            String json = JsonUtils.objectToJson(pictureResult);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            pictureResult.setCode(1);
            pictureResult.setMsg("上传失败");
            Map map = new HashMap();
            map.put("src", null);
            pictureResult.setData(map);
            String json = JsonUtils.objectToJson(pictureResult);
            return json;
        }
    }*/
    @RequestMapping(value = "/pic/upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传图片", notes = "上传图片信息")
    public String picUpload(HttpServletRequest request, @RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        FileInputStream fileInputStream = (FileInputStream) uploadFile.getInputStream();
        //生成随机名称
        String saveFileName = UUID.randomUUID().toString().replace("-", "");
        QiNiuUtil.upload2Qiniu(fileInputStream, saveFileName);
        PictureResult pictureResult = new PictureResult();
        pictureResult.setCode(0);
        pictureResult.setSrc(QiNiuUtil.qiniu_img_url_pre + saveFileName);
        String json = JsonUtils.objectToJson(pictureResult);
        return json;
    }
}
